package org.edu.common.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.edu.common.system.vo.LoginUser;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

/**
 * mybatis 拦截dao层的操作，自动填充数据
 *
 * @version 1.0
 * @since 2020-04-08
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class MybatisOptInterceptor implements Interceptor {
    /**
     * 名称要和entity对应，不是和数据库对应
     * id
     */
    public final static String FIELD_ID = "id";
    /**
     * 名称要和entity对应，不是和数据库对应
     * id
     */
    public final static String FIELD_TER = "terminalId";

    /**
     * 创建时间
     */
    public final static String FIELD_CREATE = "createDate";

    /**
     * 创建人
     */
    public final static String FIELD_CREATOR = "createBy";

    /**
     * 创建人名称
     */
    public final static String FIELD_CRTNAME = "createName";


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 第一个参数为MappedStatement， Executor的update方法的内置参数
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // 得到sql类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        // 参数
        Object args = invocation.getArgs()[1];
        if (SqlCommandType.INSERT.equals(sqlCommandType)) {
            insertFill(args);
        } else if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
            updateFill(args);
        }
        // 继续执行该执行的方法
        return invocation.proceed();
    }

    /**
     * 新增时填充
     *
     * @param o
     * @throws IllegalAccessException

     * @since 2020-04-08
     */
    private void insertFill(Object o) throws IllegalAccessException {
        //创建时间
        Object gmtCreate = getFieldValByName(FIELD_CREATE, o);
        if (gmtCreate == null) {
            setFieldValByName(FIELD_CREATE,      DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"), o);
        }
        //id
     /*   Object id = getFieldValByName(FIELD_ID, o);
        if (id == null || StrUtil.isBlank(id.toString())) {
            setFieldValByName(FIELD_ID, IdUtil.simpleUUID(), o);
        }*/
        Object id = getFieldValByName(FIELD_TER, o);
        if (id == null || StrUtil.isBlank(id.toString())) {
            setFieldValByName(FIELD_TER, 0, o);
        }

        //创建人
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser != null && loginUser.getId() != null) {
            Object gmtCreator = getFieldValByName(FIELD_CREATOR, o);
            if (gmtCreator == null || StrUtil.isBlank(gmtCreator.toString())) {
                setFieldValByName(FIELD_CREATOR, loginUser.getId(), o);
                setFieldValByName(FIELD_CRTNAME, loginUser.getRealname(), o);
            }
        }

    }

    /**
     * 更新时填充
     *
     * @param o
     * @throws IllegalAccessException

     * @since 2020-04-08
     */
    private void updateFill(Object o) throws IllegalAccessException {
 /*       //更新时间
        setFieldValByName(FIELD_MODIFIED, DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"), o);

        //更新人
        final UserSession loginUser = UserUtil.getLoginUser();
        if (loginUser != null) {
            setFieldValByName(FIELD_MODIFIEDBY, loginUser.getId(), o);
            setFieldValByName(FIELD_MFYNAME, loginUser.getName(), o);
        }*/
    }

    /**
     * 获取值
     *
     * @param fieldName
     * @param o
     * @return
     * @throws IllegalAccessException

     * @since 2020-04-08
     */
    private Object getFieldValByName(String fieldName, Object o) throws IllegalAccessException {
        if (o != null) {
            if (o instanceof Map) {
                for (Object value : ((Map) o).values()) {
                    return getFieldValByName(fieldName, value);
                }
            } else {
                Class<?> aClass = o.getClass();
                for (; aClass != Object.class; aClass = aClass.getSuperclass()) {//向上循环  遍历父类
                    try {
                        Field field = aClass.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        return field.get(o);
                    } catch (NoSuchFieldException e) {
                        //不存在继续查找父类
                    }
                }
            }
        }
        return null;
    }

    /**
     * 设置值
     *
     * @param fieldName
     * @param val
     * @param o
     * @throws IllegalAccessException

     * @since 2020-04-08
     */
    private void setFieldValByName(String fieldName, Object val, Object o) throws IllegalAccessException {
        if (o != null) {
            if (o instanceof Map) {
                for (Object value : ((Map) o).values()) {
                    setFieldValByName(fieldName, val, value);
                }
            } else {
                Class<?> aClass = o.getClass();
                for (; aClass != Object.class; aClass = aClass.getSuperclass()) {//向上循环  遍历父类
                    try {
                        final Field field = aClass.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        field.set(o, val);
                        break;
                    } catch (NoSuchFieldException e) {
                        //不存在继续查找父类
                    }
                }
            }
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
